package com.itcncp.ucenter.web.controller;

import com.itcncp.common.base.BaseController;
import com.itcncp.common.model.OrderCodeType;
import com.itcncp.common.util.OrderUtils;
import com.itcncp.common.util.ParamMap;
import com.itcncp.ucenter.common.ApiResult;
import com.itcncp.ucenter.common.ApiResultConstant;
import com.itcncp.ucenter.dao.model.*;
import com.itcncp.ucenter.rpc.api.UserInvoiceInfoService;
import com.itcncp.ucenter.rpc.api.UserInvoiceOpJnlService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 *
 * Created by shuitcncp on 2016/12/10.
 */
@Controller
@RequestMapping("/userInvoice")
@Api(tags = "userInvoice",value = "开票信息接口", description = "开票信息接口",
        produces = "userInvoice",consumes = "userInvoice",basePath = "/userInvoice")

public class UserInvoiceController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserInvoiceController.class);

    @Autowired
    private UserInvoiceInfoService userInvoiceInfoService;
    @Autowired
    private UserInvoiceOpJnlService userInvoiceOpJnlService;


    /**
     * 添加发票信息
     * @param request
     * @param userId
     * @param invoiceRise
     * @param invoiceIdent
     * @param addrTel
     * @param name
     * @param area
     * @param address
     * @return
     */
    @ApiResponse(code=200,message = "添加发票信息地址",response = UserInvoiceInfo.class)
    @ResponseBody
    @RequestMapping(value = "/addInvoice", method = RequestMethod.POST)
    public  Object addInvoice(HttpServletRequest request,
                              @RequestParam(required = true,defaultValue = "",value = "userId") Long userId,
                              @RequestParam(required = false,defaultValue = "",value = "invoiceRise") String invoiceRise,
                              @RequestParam(required = false,defaultValue = "",value = "invoiceIdent") String invoiceIdent,
                              @RequestParam(required = false,defaultValue = "",value = "addrTel") String addrTel,
                              @RequestParam(required = false,defaultValue = "",value = "name") String name,
                              @RequestParam(required = false,defaultValue = "",value = "area") String area,
                              @RequestParam(required = false,defaultValue = "",value = "address") String address) {

        ParamMap param = ParamMap.init(request);

        //用戶id不能爲空
        if(userId<=0){
            return new ApiResult( ApiResultConstant.APP_ILLEGAL);
        }

        //验证发票数量绑定是否超出
//        UserInvoiceInfoExample userInvoiceInfoExample = new UserInvoiceInfoExample();
//        userInvoiceInfoExample.createCriteria().andUserIdEqualTo(userId);
//        Integer isBindCount = userInvoiceInfoService.countByExample( userInvoiceInfoExample );
//        if(isBindCount>=5){
//            return  new ApiResult( ApiResultConstant.APP_INVOICE_OVERFLOW_COUNT );
//        }

        UserInvoiceInfo userInvoiceInfo = new UserInvoiceInfo();
        userInvoiceInfo.setUserId(userId);
        userInvoiceInfo.setInvoiceId(OrderUtils.createOrderId(OrderCodeType.INVOICE_ID));
        userInvoiceInfo.setInvoiceType(new Byte("1"));
        userInvoiceInfo.setAddrTel(addrTel);
        userInvoiceInfo.setInvoiceRise(invoiceRise);
        userInvoiceInfo.setInvoiceIdent(invoiceIdent);
        //是否为默认发票 1:不是默认发票 2:是默认发票
        userInvoiceInfo.setDefaultFlag(new Byte("1"));
        userInvoiceInfo.setCustomTitle(invoiceRise);
        userInvoiceInfo.setInvoiceClass(new Byte("1"));
        userInvoiceInfo.setName(name);
        userInvoiceInfo.setArea(area);
        userInvoiceInfo.setAddress(address);
        userInvoiceInfo.setCreateTime(new Date());

        Integer result =  userInvoiceInfoService.insertSelective(userInvoiceInfo);

        if(result>0){
            return  new ApiResult( ApiResultConstant.SUCCESS);
        }

        return new ApiResult( ApiResultConstant.FAILED);
    }


    /**
     * 修改发票信息地址
     * @param request
     * @param userId
     * @param invoiceId
     * @param invoiceRise
     * @param invoiceIdent
     * @param addrTel
     * @param name
     * @param area
     * @param address
     * @return
     */
    @ApiResponse(code=200,message = "修改发票信息地址",response = UserInvoiceInfo.class)
    @ResponseBody
    @RequestMapping(value = "/updateInvoice", method = RequestMethod.POST)
    public  Object updateInvoice(HttpServletRequest request,
                              @RequestParam(required = true,defaultValue = "0",value = "userId") Long userId,
                              @RequestParam(required = true,defaultValue = "0",value = "invoiceId") Long invoiceId,
                              @RequestParam(required = false,defaultValue = "",value = "invoiceRise") String invoiceRise,
                              @RequestParam(required = false,defaultValue = "",value = "invoiceIdent") String invoiceIdent,
                              @RequestParam(required = false,defaultValue = "",value = "addrTel") String addrTel,
                              @RequestParam(required = false,defaultValue = "",value = "name") String name,
                              @RequestParam(required = false,defaultValue = "",value = "area") String area,
                              @RequestParam(required = false,defaultValue = "",value = "address") String address) {

        ParamMap param = ParamMap.init(request);

        //用戶id不能爲空
        if(userId<=0){
            return new ApiResult( ApiResultConstant.APP_ILLEGAL);
        }

        //开票信息id不能爲空
        if(invoiceId<=0){
            return new ApiResult( ApiResultConstant.APP_ILLEGAL);
        }

        //验证发票数量绑定是否超出
//        UserInvoiceInfoExample userInvoiceInfoExample = new UserInvoiceInfoExample();
//        userInvoiceInfoExample.createCriteria().andUserIdEqualTo(userId);
//        Integer isBindCount = userInvoiceInfoService.countByExample( userInvoiceInfoExample );
//        if(isBindCount>=5){
//            return  new ApiResult( ApiResultConstant.APP_INVOICE_OVERFLOW_COUNT );
//        }

        UserInvoiceInfo userInvoiceInfo = new UserInvoiceInfo();
        userInvoiceInfo.setUserId(userId);
        userInvoiceInfo.setInvoiceId(invoiceId);
        userInvoiceInfo.setAddrTel(addrTel);
        userInvoiceInfo.setInvoiceRise(invoiceRise);
        userInvoiceInfo.setInvoiceIdent(invoiceIdent);
        userInvoiceInfo.setCustomTitle(invoiceRise);
        userInvoiceInfo.setName(name);
        userInvoiceInfo.setArea(area);
        userInvoiceInfo.setAddress(address);

        Integer result =  userInvoiceInfoService.updateByPrimaryKeySelective(userInvoiceInfo);

        if(result>0){
            return  new ApiResult( ApiResultConstant.SUCCESS);
        }

        return new ApiResult( ApiResultConstant.FAILED);
    }


    /**
     * 发票信息地址
     * @return
     */
    @ResponseBody
    @ApiResponse(code=200,message = "发票信息地址",response =UserRechangeOpJnl.class)
    @RequestMapping(value = "/findInvoiceList", method = RequestMethod.POST)
    public Object findInvoiceList(HttpServletRequest request,
                               @RequestParam(required = false, defaultValue = "0", value = "pageSize") int pageSize,
                               @RequestParam(required = false, defaultValue = "5", value = "pageIndex") int pageIndex,
                               @RequestParam(required = false, defaultValue = "", value = "userId") Long userId){

        if(userId <= 0){
            return new ApiResult( ApiResultConstant.APP_ILLEGAL );
        }

        UserInvoiceInfoExample userInvoiceInfoExample = new UserInvoiceInfoExample();
        userInvoiceInfoExample.createCriteria().andUserIdEqualTo( userId );

        //分页查询
        List<UserInvoiceInfo> userInvoiceInfos = userInvoiceInfoService
                .selectByExampleForStartPage(userInvoiceInfoExample, pageSize, pageIndex);

        return new ApiResult( ApiResultConstant.SUCCESS,userInvoiceInfos);
    }

    /**
     * 删除发票信息
     * @return
     */
    @ResponseBody
    @ApiResponse(code=200,message = "删除发票信息",response =UserRechangeOpJnl.class)
    @RequestMapping(value = "/delInvoice", method = RequestMethod.POST)
    public Object delInvoice(HttpServletRequest request,
                                   @RequestParam(required = false, defaultValue = "0", value = "invoiceId") Long invoiceId){
        //开票信息id不能爲空
        if(invoiceId<=0){
            return new ApiResult( ApiResultConstant.APP_ILLEGAL);
        }

        Integer result = userInvoiceInfoService.deleteByPrimaryKey(invoiceId);

        if(result > 0){
            return  new ApiResult( ApiResultConstant.SUCCESS);
        }

        return new ApiResult( ApiResultConstant.FAILED);
    }


    /**
     * 开通行发票
     * @param request
     * @param userId
     * @param invoiceId
     * @param tripCnt
     * @param invoiceAmount
     * @return
     */
    @ApiResponse(code=200,message = "开通行发票",response = UserInvoiceInfo.class)
    @ResponseBody
    @RequestMapping(value = "/andInvoiceOpJnl", method = RequestMethod.POST)
    public  Object andInvoiceOpJnl(HttpServletRequest request,
                                 @RequestParam(required = true,defaultValue = "0",value = "userId") Long userId,
                                 @RequestParam(required = true,defaultValue = "0",value = "invoiceId") Long invoiceId,
                                 @RequestParam(required = false,defaultValue = "",value = "tripCnt") String tripCnt,
                                   @RequestParam(required = false,defaultValue = "",value = "remark") String remark,
                                 @RequestParam(required = false,defaultValue = "0",value = "invoiceAmount") BigDecimal invoiceAmount) {

        ParamMap param = ParamMap.init(request);

        //用戶id不能爲空
        if(userId<=0){
            return new ApiResult( ApiResultConstant.APP_ILLEGAL);
        }

        //开票信息id不能爲空
        if(invoiceId<=0){
            return new ApiResult( ApiResultConstant.APP_ILLEGAL);
        }

        UserInvoiceOpJnl userInvoiceOpJnl = new UserInvoiceOpJnl();
        userInvoiceOpJnl.setInvoiceNo(OrderUtils.createOrderId(OrderCodeType.INVOICE_NO));
        userInvoiceOpJnl.setUserId(userId.toString());
        userInvoiceOpJnl.setInvoiceId(invoiceId);
        userInvoiceOpJnl.setTripCnt(tripCnt);
        userInvoiceOpJnl.setInvoiceAmount(invoiceAmount);
        userInvoiceOpJnl.setInvoiceDate(new Date());
        userInvoiceOpJnl.setBeginTime(new Date());
        userInvoiceOpJnl.setEndTime(new Date());
        //开票状态 1、已开 2、已寄出 3、已签收
        userInvoiceOpJnl.setInvoiceState(new Byte("1"));
        //b备注
        userInvoiceOpJnl.setRemark("本次共开具"+remark+"次通行记录费用");

        Integer result =  userInvoiceOpJnlService.addUserInvoiceOpJnl(userInvoiceOpJnl);

        if(result>0){
            return  new ApiResult( ApiResultConstant.SUCCESS);
        }

        return new ApiResult( ApiResultConstant.FAILED);
    }


    /**
     * 发票信息地址
     * @return
     */
    @ResponseBody
    @ApiResponse(code=200,message = "我的开票信息",response =UserRechangeOpJnl.class)
    @RequestMapping(value = "/findInvoiceOpJnlList", method = RequestMethod.POST)
    public Object findInvoiceOpJnlList(HttpServletRequest request,
                                  @RequestParam(required = false, defaultValue = "0", value = "pageSize") int pageSize,
                                  @RequestParam(required = false, defaultValue = "5", value = "pageIndex") int pageIndex,
                                  @RequestParam(required = false, defaultValue = "", value = "userId") Long userId){

        if(userId <= 0){
            return new ApiResult( ApiResultConstant.APP_ILLEGAL );
        }

        UserInvoiceOpJnlExample userInvoiceOpJnlExample = new UserInvoiceOpJnlExample();
        userInvoiceOpJnlExample.createCriteria().andUserIdEqualTo( userId.toString() );

        //分页查询
        List<UserInvoiceOpJnl> userInvoiceOpJnls = userInvoiceOpJnlService
                .selectByExampleForStartPage(userInvoiceOpJnlExample, pageSize, pageIndex);

        //查询该用户所有发票记录
        UserInvoiceInfoExample userInvoiceInfoExample = new UserInvoiceInfoExample();
        userInvoiceInfoExample.createCriteria().andUserIdEqualTo(userId);
        List<UserInvoiceInfo> userInvoiceInfos = userInvoiceInfoService.selectByExample(userInvoiceInfoExample);

        //遍历所有的开票信息
        for (int i =0 ;i<userInvoiceOpJnls.size();i++){
            Long invoiceId = userInvoiceOpJnls.get(i).getInvoiceId();
            for (int j=0;j<userInvoiceInfos.size();j++){
                UserInvoiceInfo userInvoiceInfo = userInvoiceInfos.get(j);
                if(invoiceId.equals(userInvoiceInfo.getInvoiceId())){
                    userInvoiceOpJnls.get(i).setRemark(userInvoiceInfo.getRemark());
                    userInvoiceOpJnls.get(i).setAddress(userInvoiceInfo.getAddress());
                    userInvoiceOpJnls.get(i).setArea(userInvoiceInfo.getArea());
                    userInvoiceOpJnls.get(i).setName(userInvoiceInfo.getName());
                    userInvoiceOpJnls.get(i).setInvoiceIdent(userInvoiceInfo.getInvoiceIdent());
                    userInvoiceOpJnls.get(i).setInvoiceRise(userInvoiceInfo.getInvoiceRise());
                    userInvoiceOpJnls.get(i).setAddrTel(userInvoiceInfo.getAddrTel());
                }
            }
        }

        return new ApiResult( ApiResultConstant.SUCCESS,userInvoiceOpJnls);
    }


}